package com.njust.RateMyTray_backend.config;

import com.njust.RateMyTray_backend.entity.User;
import com.njust.RateMyTray_backend.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    @Override // 判断是否支持参数解析
    public boolean supportsParameter(MethodParameter parameter) {
        // 判断参数类型是否为 User 类，并且是否标注了 CurrentUser 注解
        return parameter.getParameterType().isAssignableFrom(User.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override // 解析参数
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Claims claims = JwtAuthInterceptor.getCurrentUserClaims(); // 获取当前用户信息
        if (claims == null) {
            return null; // 如果用户信息为空，返回 null
        }
        String username = claims.getSubject(); // 获取用户名
        // 使用MyBatis-Plus 的 Lambda 查询，根据用户名查询用户信息
        return userService.lambdaQuery().eq(User::getUsername, username).one();
    }
} 